package dag

import (
	"gitee.com/gitee-go/core"
	"gitee.com/gitee-go/core/model/pipeline"
	"gitee.com/gitee-go/server/comm"
	"gitee.com/gitee-go/utils"
	"sync"
	"time"
)

var (
	mainDAGlk   sync.Mutex
	dagTemplate = `
# 结构概览
version:
  type: enum  # string,enum,mixed
  rule: [ "1.0" ]
  displayName: 配置描述版本号
  description: 配置描述文件版本号,目前只有 1.0
  required: true

triggers:
  type: enum
  rule: ['push','pr']
  displayName: 触发规则
  description: 触发规则
  required: true
`
)

func GetDAG() (string, error) {
	mainDAGlk.Lock()
	defer mainDAGlk.Unlock()
	return dagTemplate, nil
}

func SetDAG(content string) (bool, error) {
	mainDAGlk.Lock()
	defer mainDAGlk.Unlock()

	dagTemplate = content
	err := InsertDAG(content)
	if err != nil {
		core.Log.Errorf("InsertDAG err:%v", err)
		return false, err
	}
	return true, nil
}

func InitDAG() {
	db := comm.DBMain.GetDB()
	d := &pipeline.TDag{}
	ok, err := db.Desc("create_time").Limit(0, 0).Get(d)
	if err != nil {
		core.Log.Errorf("InitDAG err:%v", err)
	}
	if ok {
		dagTemplate = d.DagContent
		return
	}
	err = InsertDAG(dagTemplate)
	if err != nil {
		core.Log.Errorf("InsertDAG err:%v", err)
	}
}

func InsertDAG(content string) error {
	db := comm.DBMain.GetDB()
	dag := &pipeline.TDag{
		Id:         utils.NewXid(),
		DagContent: content,
		CreateTime: time.Now(),
	}
	_, err := db.Insert(dag)
	if err != nil {
		return err
	}
	return nil
}
